package com.TeaManage.servlet;

import com.TeaManage.bean.Customer;
import com.TeaManage.util.GokJDBCUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;

@WebServlet(name = "RegisterServlet", urlPatterns = "/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        
        String customerName = request.getParameter("customerName");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");
        String genderStr = request.getParameter("gender");
        
        // 验证必填字段
        if (customerName == null || customerName.trim().isEmpty() ||
            phone == null || phone.trim().isEmpty() ||
            password == null || password.trim().isEmpty() ||
            confirmPassword == null || confirmPassword.trim().isEmpty()) {
            request.setAttribute("error", "姓名、手机号和密码不能为空");
            request.getRequestDispatcher("/views/login.jsp").forward(request, response);
            return;
        }
        
        // 验证手机号格式
        if (!isValidPhone(phone)) {
            request.setAttribute("error", "请输入正确的手机号格式");
            request.getRequestDispatcher("/views/login.jsp").forward(request, response);
            return;
        }

        // 验证密码长度
        if (password.length() < 6) {
            request.setAttribute("error", "密码长度不能少于6位");
            request.getRequestDispatcher("/views/login.jsp").forward(request, response);
            return;
        }

        // 验证密码确认
        if (!password.equals(confirmPassword)) {
            request.setAttribute("error", "两次输入的密码不一致");
            request.getRequestDispatcher("/views/login.jsp").forward(request, response);
            return;
        }

        // 验证邮箱格式（如果填写了邮箱）
        if (email != null && !email.trim().isEmpty() && !isValidEmail(email)) {
            request.setAttribute("error", "请输入正确的邮箱格式");
            request.getRequestDispatcher("/views/login.jsp").forward(request, response);
            return;
        }
        
        try {
            // 检查手机号是否已存在
            String checkSql = "SELECT COUNT(*) FROM customer WHERE phone = ?";
            Long count = GokJDBCUtil.queryForObject(checkSql, Long.class, phone);
            
            if (count != null && count > 0) {
                request.setAttribute("error", "该手机号已被注册，请使用其他手机号");
                request.getRequestDispatcher("/views/login.jsp").forward(request, response);
                return;
            }
            
            // 处理性别
            Integer gender = null;
            if (genderStr != null && !genderStr.trim().isEmpty()) {
                try {
                    gender = Integer.parseInt(genderStr);
                } catch (NumberFormatException e) {
                    // 忽略性别格式错误，设为null
                }
            }
            
            // 插入新客户
            String insertSql = "INSERT INTO customer (customer_name, phone, email, password, gender, status) VALUES (?, ?, ?, ?, ?, 1)";
            int result = GokJDBCUtil.update(insertSql, 
                customerName.trim(), 
                phone.trim(), 
                email != null && !email.trim().isEmpty() ? email.trim() : null,
                password,
                gender
            );
            
            if (result > 0) {
                // 注册成功
                request.setAttribute("success", "注册成功！请使用手机号和密码登录");
                request.getRequestDispatcher("/views/login.jsp").forward(request, response);
            } else {
                request.setAttribute("error", "注册失败，请稍后重试");
                request.getRequestDispatcher("/views/login.jsp").forward(request, response);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "系统错误，注册失败，请稍后重试");
            request.getRequestDispatcher("/views/login.jsp").forward(request, response);
        }
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // GET请求重定向到登录页面
        response.sendRedirect("views/login.jsp");
    }
    
    private boolean isValidPhone(String phone) {
        // 简单的手机号验证：11位数字，以1开头
        String phonePattern = "^1[3-9]\\d{9}$";
        return phone != null && phone.matches(phonePattern);
    }
    
    private boolean isValidEmail(String email) {
        // 简单的邮箱格式验证
        String emailPattern = "^[A-Za-z0-9+_.-]+@([A-Za-z0-9.-]+\\.[A-Za-z]{2,})$";
        return email != null && email.matches(emailPattern);
    }
}
